package carson.web.mvc.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by prepa on 2017-03-09.
 */
public class JsonHelper {
    private static ObjectMapper objectMapper;

    //单例模式获取objectMapper
    public static ObjectMapper getObjectMapper() {
        if (null == objectMapper) {
            synchronized (ObjectMapper.class) {
                if (null == objectMapper) {
                    objectMapper = new ObjectMapper();
                }
            }
        }
        return objectMapper;
    }

    public static String toJsonString(Object object) {
        try {
            return getObjectMapper().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T toObject(String jsonString, Class<T> tClass) {
        try {
            return getObjectMapper().readValue(jsonString, tClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T toObject(InputStream inputStream, Class<T> tClass) {
        try {
            return getObjectMapper().readValue(inputStream, tClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
